<template>
	<view class="active">
		<page-head :transparent='false'>
		    <slot slot="title">{{title.length>10?title.substr(0,10)+'...':title}}</slot>
		</page-head>
		<!-- S = banner图1-->
		<image class="banner1" :src="imgUrl.img1" alt="通票活动图片1" mode="widthFix"></image>
		<image class="banner1" :src="imgUrl.img2" alt="通票活动图片2" mode="widthFix"></image>
		<!-- E = banner图1-->

		<!-- S = 按钮功能-->
		<view class="button-act">
			<view class="btn1">
				<image class="conpouns" :src="imgUrl.img3" mode="aspectFit"></image>
			</view>
			<view class="btn2">
				<view class="mock" @click="btnClick"></view>
				<image :src="imgUrl.img4" mode="aspectFill"></image>
				<!-- <image :src="imgUrl.img4_2" mode="aspectFill" v-else></image> -->
			</view>
		</view>
		<!-- E = 按钮功能-->

		<!-- S = banner图2 -->
		<image class="banner1" :src="imgUrl.img5" mode="widthFix"></image>
		<!-- E = banner图2 -->

		<!-- S =时间和消息滚动-->
		<view class="timers">
			<view v-for="(item, i) in dataBase" :key="i">
				<view :class="item.timer1" class="times">
					<text class="clock">{{item.name}}</text>
					<text class="num">还剩{{item.count}}张</text>
				</view>
			</view>
		</view>
		<view class="listScroll">
			<view class="box">
				<view class="bo2" :class="animate">
					<text class="text" v-for="(item, i) in prizeList" :key="i">
						恭喜&nbsp;{{item.mobile}}&nbsp;用户&nbsp;&nbsp;&nbsp;&nbsp;获得1张面值<text class="red">{{item.price}}元</text>门票
					</text>
				</view>
			</view>
		</view>
		<!-- E = 时间和消息滚动-->

		<!-- S = 商品图片-->
		<view class="navbar">
			<image :src="imgUrl.img8" mode="widthFix"></image>
		</view>
		<view class="list-box">
			<view class="list" v-for="(data, index2) in listGoods" :key="index2 + '10'">
				<image class="img_x" :src="data.img" mode="widthFix" @click="linkTo(data.imgurl)"></image>
			</view>
		</view>
		<!-- E = 商品图片-->

		<!-- S = 弹框图片-->
		<view class="mask update-view" v-if="updateOrNot">
			<view class="update-tip-view">
				<view class="update-tip">
					<image :src="linkImg" mode="widthFix"></image>
				</view>
				<view id="update-qrcode" v-if="showQrcode">
					<tki-qrcode ref="qrcode" :val="val" :size="size" :unit="unit" :lv="lv" :onval="onval" :loadMake="loadMake"
					 :usingComponents="true" @result="qrs" />
				</view>
				<view class="update-btn" v-if="showQrcode">
					<view class="btn-to-update" @click="toUpdateApp">
						<text class="btn-txt">请截图保存</text>
					</view>
				</view>
				<view class="close-update" @click="closeUpdate">
					<image src="../../static/img/sy/close.png" mode="widthFix"></image>
				</view>
			</view>
		</view>
		<!-- E = 弹框图片-->
	</view>
</template>

<script>
	// import Name from './components/Name.vue'
	import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue";
	let clickTime = 1;
	export default {
		components: {
			tkiQrcode
		},
		data() {
			return {
				val: '',
				size: 200,
				unit: 'upx',
				lv: 3,
				onval: false,
				loadMake: true,
				imgUrl: {
					img1: '../../static/img/cctvActive/activeBanner1.jpg',
					img2: '../../static/img/cctvActive/activeBanner2.jpg',
					img3: '../../static/img/cctvActive/coupons.jpg',
					img4: '../../static/img/cctvActive/coupons_button.jpg',
					img4_2: '../../static/img/cctvActive/coupons_button2.jpg',
					img5: '../../static/img/cctvActive/tips.jpg',
					img6: '../../static/img/cctvActive/box.jpg',
					img7: '../../static/img/cctvActive/bg2.jpg',
					img8: '../../static/img/cctvActive/navbar.jpg'
				},
				dataBase: [],
				timer1: 'timer1',
				prizeList: [],
				intNum: undefined,
				listGoods: [],
				url: [
					'../selfdetail/selfdetail?skuId=3384&cid=413&title=飞利浦(PHILIPS) 电动牙刷 成人声波震动(自带刷头*1) 蓝色&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3385&cid=412&title=苏泊尔 （SUPOR）电饭煲电饭锅5L大容量球釜内胆一键柴火饭&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3386&cid=391&title=炊大皇不粘锅32cm内圆底聚油一体压铸无铆钉易清洗 燃气煤气灶明火使用 &seller=京东自营',
					'../selfdetail/selfdetail?skuId=3387&cid=351&title=美的（Midea）破壁机家用多功能加热破壁料理机智能预约果汁机辅食机榨汁机&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3388&cid=125&title=俏香阁 每日坚果 坚果炒货礼盒8袋装 碧根果巴旦木 俏礼聚福1557g/盒&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3389&cid=252&title=中粮集团中茶牌 茶叶 普洱茶 生熟合装龙凤印礼盒装714g&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3390&cid=488&title=SWAROVSKI 施华洛世奇 双圆环设计 CIRCLE 项链女锁骨链女时尚饰品&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3391&cid=385&title=卡西欧（CASIO）手表 G-SHOCK小泥王男士防尘防泥指南针运动手表石英表&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3392&cid=239&title=漫步者（EDIFIER）TWS3 真无线蓝牙耳机 运动耳机 迷你入耳式手机耳机通用&seller=京东自营',
					'../selfdetail/selfdetail?skuId=3393&cid=395&title=虎牌（Tiger）保温杯真空轻便男女水杯MMZ-A50C-WP&seller=京东自营'
				],
				isclick: true, // 防止连续点击
				animate: '', // 初始化消息滚动为false
				updateOrNot: false, // 是否显示弹出框
				src: '/static/img/',
				linkImg: '',
				title:'央视通票',
				showQrcode: false // 是否展示二维码
			}
		},
		onShow() {
			this.genToken();
			document.title = '央视通票'
		},
		onLoad() {
			// const that = this
			// if (event.token != '' && event.token != 'null' && event.token != null && event.token != undefined && event.token !=
			// 	'undefined') {
			// 	uni.setStorageSync('token', event.token);
			// 	uni.setStorageSync('bump', event.bump);
			// 	uni.setStorageSync('relationId', event.relationId);
			// 	uni.setStorageSync('mobile', event.customerId);
			// }
		},
		methods: {
			genToken() {
				const that = this
				let url = window.location.href;
				console.log("url===" + url);
				let reg_url = /^[^\?]+\?([\w\W]+)$/,
					reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
					arr_url = reg_url.exec(url),
					ret = {};
				if (arr_url && arr_url[1]) {
					let str_para = arr_url[1],
						result;
					while ((result = reg_para.exec(str_para)) != null) {
						ret[result[1]] = result[2];
					}
				}
				let token = ret.token;
				console.log("token==" + token);
				if (token != '' && token != 'null' && token != null && token != undefined && token != 'undefined') {
					uni.setStorageSync('token', decodeURI(token));
				}
				setInterval(that.scroll, 1000)
				that.goodList()
				that.dialog()
				that.genNum()
			},
			subStr(mobile) {
				// 用户手机号重新编码
				return mobile.substr(0, 3) + "****" + mobile.substr(7)
			},
			qrs(res) {
				this.src = res
			},
			linkTo(url) {
				if (url != '') {
					uni.navigateTo({
						url: decodeURI(url)
					});
				}
			},
			scroll() { // 滚动中触发
				if (this.prizeList.length > 5) {
					this.animate = 'anim' // 在消息向上滚动的时候需要添加css3过渡动画，所以需要设置true
					setTimeout(() => {
						this.prizeList.push(this.prizeList[0]); // 将数组的第一个元素添加到数组的
						this.prizeList.shift(); // 删除数组的第一个元素
						this.animate = ''
					}, 500)
				} else {
					clearInterval()
				}
			},
			nowTime() { // 切换时间、颜色
				let nowTime = Number(new Date().getHours())
				if (0 < nowTime && nowTime < 8) {
					this.dataBase.map((item, i) => {
						if (i === 0) {
							item.isShow = true
						} else {
							item.isShow = false
						}
						// item.num = [30, 30, 50, 40, 50][i]
					})

				} else if (8 <= nowTime && nowTime < 12) {
					this.dataBase.map((item, i) => {
						if (i === 1) {
							item.isShow = true
						} else {
							item.isShow = false
						}
						this.dataBase[0].count = 0
						// console.log(item.num = [30, 30, 50, 40, 50][i])
					})
				} else if (12 <= nowTime && nowTime < 16) {
					this.dataBase.map((item, i) => {
						if (i === 2) {
							item.isShow = true
						} else {
							item.isShow = false
						}
						this.dataBase[0].count = 0
						this.dataBase[1].count = 0
					})
				} else if (16 <= nowTime && nowTime < 20) {
					this.dataBase.map((item, i) => {
						if (i === 3) {
							item.isShow = true
						} else {
							item.isShow = false
						}
						this.dataBase[0].count = 0
						this.dataBase[1].count = 0
						this.dataBase[2].count = 0
					})
				} else {
					this.dataBase.map((item, i) => {
						if (i === 4) {
							item.isShow = true
						} else {
							item.isShow = false
						}
						this.dataBase[0].count = 0
						this.dataBase[1].count = 0
						this.dataBase[2].count = 0
						this.dataBase[3].count = 0
					})
				}
				this.dataBase.map((item, i) => {
					// console.log(item)
					if (item.isShow == true) {
						// console.log(1)
						item.timer1 = 'timer1'
					} else {
						item.timer1 = ''
					}
				})
				// console.log(this.dataBase)
			},
			goodList() {
				this.url.map((item, i) => {
					this.listGoods.push({
						img: `../../static/img/cctvActive/xs1-${i + 1}.jpg`,
						imgurl: item
					})
				})
			},
			btnClick(e) { //点击按钮事件
				e.stopPropagation()
				this.imgUrl.img4 = '../../static/img/cctvActive/coupons_button2.jpg'
				// this.isclick = false
				setTimeout(() => {
					this.imgUrl.img4 = '../../static/img/cctvActive/coupons_button.jpg'
					// this.isclick = !this.isclick
					// this.updateOrNot = true
					// this.dialog()
				}, 100);
				if (this.isclick == true) {
					this.isclick = false;
					this.qpClick()
					this.clickDown();
				} else {
					uni.showToast({
						icon: 'none',
						title: '请勿频繁点击！'
					});
				}
			},
			clickDown() {
				var that = this;
				let it = setTimeout(function() {
					that.isclick = false;
					clickTime--;
					if (clickTime == 0) {
						console.log('111111');
						that.isclick = true;
						clickTime = 1;
						clearTimeout(it)
					}
				}, 1000)
			},
			async qpClick() { // 点击按钮信息
				const that = this;
				try {
					uni.request({
						url: this.$usereq + '/coupon-admin/ystp/buy',
						method: 'POST',
						dataType: 'json',
						header: {
							'blade-auth': decodeURI(uni.getStorageSync('token')),
							'content-type': 'application/x-www-form-urlencoded'
						},
						success: res => {
							if (res.data.code === 201) { // 抱歉，当前时段的票已抢完   203, "", "每人只能抢一次~
								that.updateOrNot = true
								that.showQrcode = false
								that.linkImg = `../../static/img/cctvActive/dialog${2}.png`
							} else if (res.data.code === 202) { // 您已经抢过票啦~
								that.updateOrNot = true
								that.showQrcode = true
								that.linkImg = `../../static/img/cctvActive/dialog${3}.png`
								that.val = res.data.data.ckey
								// console.log(that.val)
							} else if (res.data.code === 204) { // 恭喜您抢到票啦~
								that.updateOrNot = true
								that.showQrcode = true
								that.linkImg = `../../static/img/cctvActive/dialog${4}.png`
								that.val = res.data.data.ckey
								// that.prizeList.concat(res.data.data)
								that.genNum()
								that.dialog()
							} else if (res.data.code === 101) {
								that.updateOrNot = false
								that.showQrcode = false
								uni.showToast({
									title: '抢购失败，请稍后重试',
								})
							} else if (res.data.code === 203) {
								that.updateOrNot = false
								uni.showToast({
									title: '每人只能抢一次~'
								})
							} else if (res.data.code === 205) { // 还未到抢票时间~
								that.updateOrNot = true
								that.showQrcode = false
								that.linkImg = `../../static/img/cctvActive/dialog${1}.png`
							} else if (res.data.code === 206) { // 功能到时间~
								that.updateOrNot = true
								that.showQrcode = false
								that.linkImg = `../../static/img/cctvActive/dialog${5}.png`
							}
						}
					});
					// let res = await that.$request.post('/coupon-admin/ystp/buy', {} );
					// console.log(res)
				} catch (e) {
					console.log('loading hot goods list fail' + e);
				}
			},
			async dialog() { // 滚动信息
				try {
					uni.request({
						url: this.$usereq + '/coupon-admin/ystp/topInfo',
						method: 'GET',
						dataType: 'json',
						header: {
							'content-type': 'application/json',
							'blade-auth': decodeURI(uni.getStorageSync('token'))
						},
						success: res => {
							let datas = res.data;
							if (datas.code == 200) {
								this.prizeList = res.data.data;
							} else if (datas.code == 401) {
								// this.valida();
								uni.showToast({
									icon: 'none',
									title: datas.msg
								});
							} else {
								uni.showToast({
									icon: 'none',
									title: datas.msg
								});
							}
						}
					});
				} catch (e) {
					uni.hideLoading();
					console.log(e.message);
				}
				// try{
				// 	let res = await this.$request.get('/coupon-admin/ystp/topInfo', {} );
				// 	if(res.data.code === 200 && res.data) {
				// 		// console.log(res.data.data)
				// 		
				// 	}
				// 	
				// } catch(e) {
				// 	console.log('loading hot goods list fail' + e);
				// }
			},
			async genNum() { //  库存查看
				const that = this;
				try {
					uni.request({
						url: this.$usereq + '/coupon-admin/ystp/stock',
						method: 'GET',
						dataType: 'json',
						header: {
							'content-type': 'application/json',
							'blade-auth': decodeURI(uni.getStorageSync('token'))
						},
						success: res => {
							if (res.data.code === 200 && res.data) {
								// console.log(res.data)
								// res.data.data.map((item, i) => {
								// 	// console.log(item)
								// 	that.dataBase.map((items, index) => {
								// 		if (i === index){
								// 			items.num = item.count
								// 		}
								// 	})
								// })
								that.dataBase = res.data.data;
							}
							that.nowTime()
						}
					});
					// let res = await that.$request.get('/coupon-admin/ystp/stock', {} );
					// if(res.data.code === 200 && res.data) {
					// 	// console.log(res.data)
					// 	res.data.data.map((item, i) => {
					// 		// console.log(item)
					// 		that.dataBase.map((items, index) => {
					// 			if (i === index){
					// 				items.num = item.count
					// 			}
					// 		})
					// 	})

					// if(that.timestamp > 0) {
					// 	that.nowTime()
					// } else {
					// 	this.dataBase.map((item, i) => {
					// 		item.isShow = false
					// 		item.num = 0
					// 	})
					// }
					// }
				} catch (e) {
					console.log('loading hot goods list fail' + e);
				}
			},
			toUpdateApp() { // 立即保存
				// this.$refs.qrcode._saveCode();
				// var bitmap = new plus.nativeObj.Bitmap();
				// 加载海报图片
				// 	bitmap.loadBase64Data(_this.poster, function() {
				// 		//保存到系统相册
				// 		bitmap.save("doc/poster"+_this.coupon.item_id+".jpg", {
				// 			overwrite: true, //是否覆盖已有图片， true 是
				// 			quality: 100 //图片质量，1-100 默认50， 100质量最高
				// 		}, function(e) {
				// 			//重点就是这里， 需要将bitmap保存的临时路径再使用saveImageToPhotosAlbum进行保存
				// 			uni.saveImageToPhotosAlbum({
				// 				filePath: e.target,
				// 				success: function () {
				// 					uni.showToast({
				// 						title: "图片保存成功",
				// 						icon: "none"
				// 					});
				// 				}
				// 			});
				// 		}, function(e) {
				// 				uni.showToast({
				// 					title: "图片保存失败",
				// 					icon: "none"
				// 				});
				// 			});
				// 		}, function(e) {
				// 			uni.showToast({
				// 				title: "图片保存失败",
				// 				icon: "none"
				// 			});
				// 	});
			},
			closeUpdate() { // 关闭弹框
				this.updateOrNot = false
			},
		},
	}
</script>

<style lang="scss" scoped>
	.active {
		width: 100%;

		.banner1 {
			width: 100%;
			display: block;
			overflow: hidden;
			overflow-y: auto;
		}

		.button-act {
			display: flex;
			flex-flow: nowrap;
			justify-content: center;
			background: url('../../static/img/cctvActive/bg.jpg') no-repeat center;
			background-size: 100% 100%;

			.btn1 {
				width: 356upx;
				height: 177upx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.btn2 {
				width: 190upx;
				height: 177upx;
				margin-left: -1px;
				position: relative;

				.mock {
					width: 48px;
					height: 36px;
					border-radius: 50%;
					// background: #fff;
					position: absolute;
					top: 34upx;
					left: 30upx;
					z-index: 10;
				}

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.timers {
			width: 100%;
			// height: 240upx;
			overflow: hidden;
			display: flex;
			flex-flow: nowrap;
			justify-content: start;

			.times {
				color: gray;
				display: flex;
				justify-content: center;
				flex-wrap: wrap;
				height: 95upx;
				background: url('../../static/img/cctvActive/box.jpg') no-repeat center;
				background-size: 100% 100%;

				.clock {
					width: 100%;
					height: 10px;
					margin-top: 20upx;
					text-align: center;
					font-size: 22upx;
				}

				.num {
					width: 100%;
					font-weight: 600;
					text-align: center;
					font-size: 30upx;
				}

			}

			.timer1 {
				color: purple;
			}

		}

		.listScroll {
			background: url('../../static/img/cctvActive/bg2.jpg') no-repeat center;
			background-size: 100% 100%;
			width: 100%;
			height: 344upx;
			display: flex;
			justify-content: center;
			flex-direction: column;

			.box {
				justify-content: center;
				margin: 0 auto;
				width: 92%;
				height: 76%;

				line-height: 1;
				overflow: hidden;
				border: 2px solid #fff;
				border-radius: 10upx;

				.bo2 {
					// position: relative;
					// transition: top 0.5s;
					display: flex;
					flex-wrap: wrap;

					.text {
						width: 100%;
						height: 53upx;
						line-height: 53upx;
						text-align: center;
						font-size: 26upx;
						color: #fff;

						.red {
							color: red;
							font-weight: 600;
							margin: 0 6upx;
						}
					}

					.text:last-child {
						margin-right: 0;
					}
				}
			}
		}

		.navbar {
			width: 100%;

			image {
				display: block;
				width: 100%;
			}
		}

		.list-box {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			background: #1b0952;
			justify-content: center;

			.list {
				width: 50%;

				.img_x {
					width: 100%
				}
			}
		}

		.update-view {
			position: fixed;
			top: 0;
			left: 0;
			z-index: 999;
			width: 100%;
			height: 100vh;
			background: rgba(0, 0, 0, 0.4);
			z-index: 6000;

			.update-tip-view {
				width: 100%;
				// width: 78%;
				// height: 700upx;
				z-index: 6666;
				position: relative;
				// position: fixed;
				// left: 00%;
				// right: 0;
				// top: 0%;
				// bottom: 0;
				// background-color: white;
				// border-radius: 20upx;

				.update-tip {
					width: 100%;
					// height: 500upx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				#update-qrcode {
					position: absolute;
					left: 36%;
					top: 44%;
					background: #fff;
					width: 200upx;
					height: 200upx;
				}

				.update-btn {
					width: 100%;
					height: 130upx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-top: 18%;
					position: absolute;
					top: 48%;

					.btn-to-update {
						width: 20%;
						// height: 32upx;
						color: white;
						border: 1px solid #fff;
						border-radius: 10upx;

						.btn-txt {
							display: flex;
							font-size: 20upx;
							justify-content: center;
							align-items: center;
						}
					}
				}

				.close-update {
					width: 60upx;
					height: 60upx;
					position: absolute;
					top: 19%;
					right: 16%;
					// margin-left: 75%;
					// margin-top: -174%;

					image {
						width: 100%;
						height: 100%;
					}
				}


			}
		}

		.anim {
			transition: all 0.5s;
			margin-top: -26px;
		}
	}
</style>
